﻿namespace SubhadraSolutions.Sharp.Utils.Windows
{
    using System.Threading;
    using System.Windows.Threading;

    using SubhadraSolutions.Sharp.Utils.Collections.Concurrent;
    using SubhadraSolutions.Sharp.Utils.Threading;

    /// <summary>
    /// The WindowsDispatcherProvider class.
    /// </summary>
    public sealed class ThreadBasedWindowsDispatcherProvider : IDispatcherProvider
    {
        /// <summary>
        /// The flyweight
        /// </summary>
        private readonly GenericFlyweight<WindowsDispatcherAdapter> flyweight;

        /// <summary>
        /// The instance object
        /// </summary>
        private static readonly ThreadBasedWindowsDispatcherProvider InstanceObject = new ThreadBasedWindowsDispatcherProvider();

        /// <summary>
        /// Prevents a default instance of the <see cref="ThreadBasedWindowsDispatcherProvider"/> class from being created.
        /// </summary>
        private ThreadBasedWindowsDispatcherProvider()
        {
             this.flyweight = new GenericFlyweight<WindowsDispatcherAdapter>(this.CreateDispatcher, false);
        }

        /// <summary>
        /// Gets the instance.
        /// </summary>
        /// <value>
        /// The instance.
        /// </value>
        public static ThreadBasedWindowsDispatcherProvider Instance
        {
            get
            {
                return InstanceObject;
            }
        }

        /// <summary>
        /// Gets the dispatcher.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <returns></returns>
        public IDispatcher GetDispatcher(object target)
        {
            var dispatcher = Dispatcher.FromThread(Thread.CurrentThread) ?? Dispatcher.CurrentDispatcher;
            return this.flyweight.GetObject(dispatcher);
        }

        /// <summary>
        /// Creates the dispatcher.
        /// </summary>
        /// <param name="dispatcher">The dispatcher.</param>
        /// <returns></returns>
        private WindowsDispatcherAdapter CreateDispatcher(object dispatcher)
        {
            return new WindowsDispatcherAdapter((Dispatcher)dispatcher);
        }
    }
}
